package com.shenbianyun.youfu;


import com.alibaba.fastjson.JSONObject;
import com.shenbianyun.bosskgpay.entity.RequestMessage;
import com.shenbianyun.bosskgpay.entity.pay.PaymentReqModel;
import com.shenbianyun.bosskgpay.utils.*;
import com.shenbianyun.youfu.entity.Payment;
import com.shenbianyun.youfu.entity.RequestMsg;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.jmeter.protocol.java.sampler.AbstractJavaSamplerClient;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;



/**
 * @Description //Jmeter 优付的批量付款 接口：30481
 * 不可固定业务参数
 **/

public class TestPaymentServiceYoufuJ extends AbstractJavaSamplerClient {


    public final String CHARSET_UTF_8 = "UTF-8";

    public final String INTER_KEY = "1499b6603373412e950e1fd4a027bb9b";
    public static String MER_PRIVATE_KEY = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALw5Kmjo7FY23ABnat0B++f4pCS0VE/yFfDYn5At3VywR/cm5rWZyeIL5KAY7y+XMmoWP4pIeRXVgPTP54x6TpW8xfrHDUXElWVjqM6KhJRgDodmETC9ICFq7OWR1iNswqJAV+O02Ga5dzUsx9z3UXLDdRAegCrVJ5XBRwN1LNZTAgMBAAECgYEApN453Kzxns7sw9nSTAYZ3eX3+UKPe3tkZpOIqKTT+gVa9Az6FuW/ZSXfu7A7imcYvL4CKCE1Fr/t9gJKIs1bGOMmaYYhr40EXcdMREWipOjOC+GLC3LSdch9kuMBAcp0pgh2Ytbqx6QLLJBwuvNiRpLY7tG8aTc2f01x9dthQ0ECQQDfSGyz83ZSJJysH4f/yQTJ00fHUKaIHoXuzVQYYU+W9nY33Yqo7Ja0boWT2SFYKk3x+TRjExS8ydm+so8eDAbzAkEA182eW8JbDeevbanpkwTUJ53+O1BGgL0WmF5TYbSPSRRGsjukEEnqU8kqfHq3VwuqEHxoiOO6acNTLzEl5T6LIQJBAMb4gi3F2f2PNLJJkubEGmlDxuX9n7kTAiTwgm0LYmJTlLtpx6OK2S1Gg/BhgE5RvI3RlfZnzYYClfBSrCiJbTMCQCfLRdlb1JiS0ZmiTG0M5eZMTxY27llNBP6h3jRVLFrof0TclJtgVfKPVONRab+GahzSJCCiBbz9BLjeEkPcraECQAPadMN/fDZZiGwxGQccaEcKczXVXLlgEWXHOFcbFHxl6g4tM9jY+7uc5+gZA/oDrSFarT0CugJd07xf9vmvJzY=";
    public static String MER_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN0YKZY/NDGrrqNTwrVyvhKUmHeJCHlB2FUqrvsaH9I8kS3TkRvQyXnUwBEhNtLEZ1ryRaB0QnwPP7rM1DkMF6tLmqjonE6T++50m0CnvgAEg+JC08//Vy9qMJHR9zx/N5VMYzaRrqsrFCfwsYerYBSeOHltkAr8UiYfoguVK5ewIDAQAB";
    public static String YOU_FU_PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN0YKZY/NDGrrqNTwrVyvhKUmHeJCHlB2FUqrvsaH9I8kS3TkRvQyXnUwBEhNtLEZ1ryRaB0QnwPP7rM1DkMF6tLmqjonE6T++50m0CnvgAEg+JC08//Vy9qMJHR9zx/N5VMYzaRrqsrFCfwsYerYBSeOHltkAr8UiYfoguVK5ewIDAQAB";
    public final String MER_ID = "89900000498316430043";
    public final String PROJECT_ID = "1610278112283347125";
    public final String API_VERSION = "V1.0";
    public final String OMS_TEST_URL = "http://192.168.40.52:8280/trans-business/clientBusiness/common.do";

    public static Long levy_id = 35503L;//30481L、35503L、35503L

    public RequestMessage rm;
    public PaymentReqModel.PayItems payItems;


    public String runTestPaymentServiceYoufuJ() throws Exception {

        /**--------————————————业务请求参数——————————————————**/
        Payment payment = new Payment();
        //商户号
        payment.setMerId(MER_ID);
        //项目Id
        payment.setProjectId(PROJECT_ID);
        //付款总笔数  这里只模拟一条
        payment.setTotalCount("1");
        //付款总金额 单位/分
        payment.setTotalAmt("1");
        //生成guid码 理论上不重复
        Long id = SnowflakeIdGeneratorFactory.getInstance().nextId();
        payment.setMerBatchId(id + "");
        //批量付款接口，项目编码
        List payItemsList = new ArrayList();
        Payment.PayItems payItems = new Payment.PayItems();
        //同批次唯一，商户生成
        payItems.setMerOrderId("OrderPay" + id);
        /**
         * 必填
         */
        payItems.setAmt(1L);
        payItems.setPayeeName("史千龙");//史千龙、崔方方
        payItems.setIdCard("130432200002150319");//130432200002150319、412828199310044519
        payItems.setPayeeAcc("6214831054850745");//6214831054850745、6214830102464327
        payItems.setMobile("19850484667");//19850484667、18001150364

        // 0 指银行卡
        payItems.setPaymentType(0);
        // 0 代付类型为实时
        payItems.setPayType(0);
        //税源地ID
        payItems.setLevyId(levy_id);
        //1：对私  0：对公（不支持）
        payItems.setAccType(1);
        /**
         * 选填
         */
        //payItems.setBranchName("北京");
        //payItems.setProvince("北京");
        //payItems.setCity("北京");
        //payItems.setBranchNo("北京");
        //payItems.setMemo("服务费贷");

        /**--------————————————去付款——————————————————————**/
        payItemsList.add(payItems);
        payment.setPayItems(payItemsList);
        String json = JsonUtils.toJson(payment);
        System.out.println("请求未加密数据:" + json);


        RequestMsg rm = new RequestMsg();
        rm.setFunCode("6001");
        rm.setMerId(MER_ID);
        rm.setVersion(API_VERSION);
        rm.setReqId(id + "");
        //加密处理
        byte[] bs = DESUtils.encrypt(json.getBytes(CHARSET_UTF_8), INTER_KEY);
        String reqDataEncrypt = Base64Utils.encodeToString(bs);
        rm.setReqData(reqDataEncrypt);
        rm.setSign(RSAUtils.sign(reqDataEncrypt, MER_PRIVATE_KEY));
        String reqStr = JsonUtils.toJson(rm);
        System.out.println("请求加密数据：" + reqStr);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("reqJson", reqStr);
        String resData = httpClientPost(OMS_TEST_URL, map);
        System.out.println("响应数据：" + resData);

        return resData;
    }


    @Override
    public SampleResult runTest(JavaSamplerContext javaSamplerContext) {
        SampleResult sampleResult = new SampleResult();
        String resData = "";

        try {
            sampleResult.sampleStart();

            resData = runTestPaymentServiceYoufuJ();
            System.out.println("reqdata：" + resData);

            // 通过下面的操作就可以将被测方法的响应输出到Jmeter的察看结果树中的响应数据里面了。
            //断言
            JSONObject jsonObject1 = JSONObject.parseObject(resData);
            if (jsonObject1.get("resCode").equals("0000")) {
                sampleResult.setResponseOK();
                sampleResult.setResponseData(true + "", SampleResult.TEXT);
                System.out.println("批量付款结果:" + true);
            } else {
                sampleResult.setSuccessful(false);
                sampleResult.setResponseData(false + " " + jsonObject1.get("resMsg"), SampleResult.TEXT);
                System.out.println("批量付款结果:" + false + " " + jsonObject1.get("resMsg"));
            }
        } catch (Exception e) {
            sampleResult.setSuccessful(false);
            sampleResult.setResponseData(resData, SampleResult.TEXT);
            sampleResult.setResponseMessage(e.toString());
        } finally {
            sampleResult.sampleEnd();
        }

        return sampleResult;
    }

    private static String getHttpResult(InputStream httpInputStream, String charset) throws IOException {
//		return IOUtils.toString(new BufferedReader(new InputStreamReader(httpInputStream, charset)));
        String readLine;
        // 当正确响应时处理数据
        StringBuffer resultBuffer = new StringBuffer();

        try (
                // 处理响应流，必须与服务器响应流输出的编码一致
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(httpInputStream, charset))) {
            while ((readLine = responseReader.readLine()) != null) {
                resultBuffer.append(readLine);
            }
        }
        return resultBuffer.toString();
    }

    public static CloseableHttpClient client = HttpClients.custom()
            .setMaxConnPerRoute(50)
            .setMaxConnTotal(200)
            .setDefaultRequestConfig(RequestConfig.custom()
                    .setConnectTimeout(5000)
                    .setSocketTimeout(10000)
                    .build())
            .setKeepAliveStrategy((response, context) -> 15 * 1000) // 设置Keepalive的时间为60s→2023-9-11 尝试规避NoHttpResponseException，与红洁/海鹏沟通，改为<60s
            .build();

    public static String httpClientPost(String urlParam, Map<String, Object> params ) {

        HttpPost httpPost = new HttpPost(urlParam);
        String charset = "UTF_8";
        Object token = params.get("token");
        // 构建请求参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> elem = iterator.next();
            list.add(new BasicNameValuePair(elem.getKey(), String.valueOf(elem.getValue())));
        }
        try {
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
                httpPost.setEntity(entity);
            }
            HttpResponse response = client.execute(httpPost);
            // 读取服务器响应数据
            return getHttpResult(response.getEntity().getContent(), charset);
        } catch (Exception e) {
            Throwable cause = e.getCause();
            //单独处理“Caused by: org.apache.http.ProtocolException: Target host is not specified”，转换成人话
            if (cause instanceof org.apache.http.ProtocolException) {
//				System.out.println("-----------------"+ cause.getMessage());Target host is not specified
                throw new RuntimeException("请确保正确设置了目标主机的URL");
            }
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        try {
        TestPaymentServiceYoufuJ j = new TestPaymentServiceYoufuJ();
        j.runTestPaymentServiceYoufuJ();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
